import requests
import json
from flask import Flask, request, jsonify
from flask_cors import CORS
import time
import pymysql
from pymysql.cursors import DictCursor

app = Flask(__name__)
CORS(app)  # 启用 CORS，允许跨域请求

# 数据库配置 - 根据实际情况修改
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': '4014',
    'database': 'lqb',
    'charset': 'utf8mb4',
    'cursorclass': DictCursor
}


@app.route('/image', methods=['POST'])
def image_message():
    try:
        # 获取前端发送的 JSON 数据
        data = request.get_json()
        # 验证数据格式
        if 'Name' not in data or 'Password' not in data or 'Image' not in data:
            raise ValueError("数据必须包含 Name 、 Password 和 Image 字段")
        print(data)

        # 检查姓名是否已存在
        if check_name_exists(data['Name']):
            return jsonify({"message": "已经注册"}), 400

        # 存储数据到数据库
        save_to_database(data['Name'], data['Password'], data['Image'])
        return jsonify({"message": "上传成功", "Name": data['Name']})
    except Exception as e:
        # 错误处理
        return jsonify({'error': str(e)}), 500


def check_name_exists(name):
    """检查姓名是否已存在于数据库中"""
    try:
        with pymysql.connect(**DB_CONFIG) as connection:
            with connection.cursor() as cursor:
                sql = "SELECT COUNT(*) as count FROM Face WHERE Name = %s"
                cursor.execute(sql, (name,))
                result = cursor.fetchone()
                return result['count'] > 0
    except pymysql.Error as e:
        print(f"数据库错误: {e}")
        raise
    except Exception as e:
        print(f"未知错误: {e}")
        raise


def save_to_database(name, password, image_data):
    """将人脸数据保存到 MySQL 数据库"""
    try:
        # 连接数据库
        with pymysql.connect(**DB_CONFIG) as connection:
            with connection.cursor() as cursor:
                # 插入数据到 Face 表
                sql = """
                      INSERT INTO Face (Name, Password, Image)
                      VALUES (%s, %s, %s)
                      """

                # 执行插入
                cursor.execute(sql, (name, password, image_data))

            # 提交事务
            connection.commit()
            print(f"人脸数据已存储，姓名: {name}")

    except pymysql.Error as e:
        print(f"数据库错误: {e}")
        raise
    except Exception as e:
        print(f"未知错误: {e}")
        raise


if __name__ == '__main__':
    app.run(debug=True, port=5002)